package com.btkj.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.mapper.helper.SimpleMapperHelper;
import com.sdicons.json.model.JSONString;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;

public class HttpUtils
{
	static
	{
		SimpleMapperHelper helper = new SimpleMapperHelper()
		{
			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			public JSONValue toJSON(Object arg0) throws MapperException
			{

				String d = format1.format(arg0);
				JSONString str = new JSONString(d);
				return str;
			}

			@SuppressWarnings("rawtypes")
			public Object toJava(JSONValue arg0, Class arg1)
					throws MapperException
			{
				Date date = null;
				try
				{
					date = format1.parse(arg0.strip().toString());
				}
				catch (ParseException e)
				{
					e.printStackTrace();
				}
				return date;
			}

			public Class<?> getHelpedClass()
			{
				return Date.class;
			}

		};
		JSONMapper.addHelper(helper);

		// // 客户端密钥库
		// String sslKeyStorePath;
		// String sslKeyStorePassword;
		// String sslKeyStoreType;
		// // 客户端信任的证书
		// String sslTrustStore;
		// String sslTrustStorePassword;
		// // 上面发布的servlet请求地址
		//
		// // 这是密钥库
		// sslKeyStorePath = "C:\\Users\\jxf\\server.jks";
		// sslKeyStorePassword = "password";
		// sslKeyStoreType = "JKS"; // 密钥库类型，有JKS PKCS12等
		// // 信任库，这里需要服务端来新人客户端才能调用，因为这个我是配置的https双向验证，不但是要客户端信任服务端，服务端也要信任客户端。
		// sslTrustStore = sslKeyStorePath;
		// sslTrustStorePassword = sslKeyStorePassword;
		//
		// System.setProperty("javax.net.ssl.keyStore", sslKeyStorePath);
		// System.setProperty("javax.net.ssl.keyStorePassword",
		// sslKeyStorePassword);
		// System.setProperty("javax.net.ssl.keyStoreType", sslKeyStoreType);
		// // 设置系统参数
		// System.setProperty("javax.net.ssl.trustStore", sslTrustStore);
		// System.setProperty("javax.net.ssl.trustStorePassword",
		// sslTrustStorePassword);
		// System.setProperty("java.protocol.handler.pkgs",
		// "sun.net.www.protocol");
	}

	public static void download(String url, String id, String localpath)
			throws IOException
	{
		String urlstr = url + "?id=" + id;
		URL getUrl = new URL(urlstr);
		HttpURLConnection connection = (HttpURLConnection) getUrl
				.openConnection();
		connection.connect();
		// ȡ������������ʹ��Reader��ȡ
		InputStream reader = connection.getInputStream();

		String fileName = localpath + File.separator + id + ".png";

		FileOutputStream filestream = new FileOutputStream(fileName);
		byte[] data = new byte[1024];

		int length = reader.read(data);
		while (length > 0)
		{
			filestream.write(data, 0, length);
			length = reader.read(data);
		}
		filestream.close();
		connection.disconnect();
	}

	public static String upload(String url, String fileName) throws IOException
	{
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl
				.openConnection();

		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		connection.connect();
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		FileInputStream file = new FileInputStream(fileName);

		byte[] data = new byte[1024];

		int length = file.read(data);
		while (length > 0)
		{
			out.write(data, 0, length);
			length = file.read(data);
		}
		out.flush();
		out.close(); // flush and close
		file.close();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), "utf-8"));
		String id = reader.readLine();
		reader.close();
		connection.disconnect();
		return id;
	}

	public static String post(String url, Object value) throws IOException,
			MapperException
	{

		JSONValue jsonValue = JSONMapper.toJSON(value);
		String jsonStr = jsonValue.render(false);
		System.out.println(jsonStr);

		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl
				.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.addRequestProperty("key", UUID.randomUUID().toString());
		connection.setRequestProperty("Content-Type",
				"application/json;charset=UTF-8");
		connection.setReadTimeout(10000);
		connection.connect();

		String id = null;

		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());

		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,
				"utf-8"));
		writer.write(jsonStr);
		writer.flush();

		out.flush();
		out.close(); // flush and close

		InputStreamReader ireader = new InputStreamReader(
				connection.getInputStream(), "utf-8");
		BufferedReader reader = new BufferedReader(ireader);
		id = reader.readLine();

		reader.close();

		connection.disconnect();
		return id;
	}

	public static String post(String url, String value) throws IOException,
			MapperException
	{
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl
				.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type", "text/json");
		connection.connect();
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());

		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,
				"utf-8"));
		writer.write(value);
		writer.flush();

		out.flush();
		out.close();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), "utf-8"));
		String id = reader.readLine();
		reader.close();
		connection.disconnect();
		return id;
	}

	public static String get(String url) throws Exception
	{
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl
				.openConnection();
		connection.connect();
		InputStream stream = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				stream, "utf-8"));
		String result = "";
		String line = reader.readLine();
		while (line != null)
		{
			result += line;
			line = reader.readLine();
		}
		connection.disconnect();
		return result;
	}

	public static Object get(String url, Class<?> clz) throws Exception
	{
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl
				.openConnection();
		connection.connect();
		InputStream stream = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				stream, "utf-8"));
		String result = "";
		String line = reader.readLine();
		while (line != null)
		{
			result += line;
			line = reader.readLine();
		}
		connection.disconnect();

		JSONParser parser1 = new JSONParser(new StringReader(result));
		JSONValue jsonValue1 = parser1.nextValue();
		Object obj = JSONMapper.toJava(jsonValue1, clz);

		return obj;
	}
}
